var app = getApp();
import { warrantyApi } from '../../../services/api';

Page({
  data: {
    buttonBounding: app.globalData.buttonBounding,
    baseInfo: {},
    pictureList: [],
    qxImgList: [],
    mergedQrPictureList: [],
    currentTime: '',
    ownerPhoneDisplay: '184****0886',
    stars: [], // 星空动画数据
    loading: true, // 加载状态
    warrantyId: null // 质保ID
  },
  onLoad(options) {
    this.initStars();
    // 从URL参数获取质保ID
    if (options.warrantyId) {
      this.setData({ warrantyId: options.warrantyId });
      this.loadWarrantyDetails(options.warrantyId);
    } else {
      console.error('质保ID参数缺失');
      this.showError('质保ID参数缺失');
    }
  },
  onShow() {
    this.initStars(); // 重新初始化星空动画
    // onShow 不需要重新加载数据，因为数据在 onLoad 时已经加载
    // 如果需要刷新数据，应该通过用户手动触发或特定场景触发
  },
  
  /**
   * 下拉刷新
   */
  async onPullDownRefresh() {
    if (this.data.warrantyId) {
      await this.loadWarrantyDetails(this.data.warrantyId);
    }
    wx.stopPullDownRefresh();
  },
  
  /**
   * 加载质保详情数据
   * @param {string} warrantyId 质保ID
   */
  async loadWarrantyDetails(warrantyId) {
    try {
      this.setData({ loading: true });
      
      console.log('正在加载质保详情，ID:', warrantyId);
      
      // 调用质保详情查询接口
      const response = await warrantyApi.queryWarrantyDetails(warrantyId);
      
      if (response.status === 200 && response.data) {
        // 处理返回的单对象数据（以前是数组，现在是单对象）
        const baseInfo = response.data;
        console.log('质保详情数据:', baseInfo);
        
        // 处理数据格式化
        this.processWarrantyData(baseInfo);
      } else {
        console.error('获取质保详情失败:', response);
        this.showError('获取质保详情失败，请稍后重试');
      }
    } catch (error) {
      console.error('加载质保详情出错:', error);
      this.showError('网络连接失败，请检查网络后重试');
    } finally {
      this.setData({ loading: false });
    }
  },
  
  /**
   * 处理质保数据格式化
   * @param {Object} baseInfo 质保详情数据
   */
  processWarrantyData(baseInfo) {
    // Format constructionDate to yyyy-MM-dd if it exists
    if (baseInfo && baseInfo.constructionDate) {
      baseInfo.constructionDate = this.formatDate(baseInfo.constructionDate);
    }
    if (baseInfo && baseInfo.createTime) {
      baseInfo.createTime = this.formatDate(baseInfo.createTime);
    }

    // Process picture list
    let pictureList = [];
    if (baseInfo && baseInfo.pictureList) {
      pictureList = baseInfo.pictureList.split('|').filter(url => url.trim());
    }
    console.log('Processed pictureList:', pictureList);

    // Process qxImg list (清晰卷号图 - 多张用 | 分隔)
    let qxImgList = [];
    if (baseInfo && baseInfo.qxImg) {
      qxImgList = baseInfo.qxImg.split('|').filter(url => url.trim());
    }
    console.log('Processed qxImgList:', qxImgList);
    
    // Process mergedQrPicture list (车架号和卷芯码合拍图 - 多张用 | 分隔)
    let mergedQrPictureList = [];
    if (baseInfo && baseInfo.mergedQrPicture) {
      mergedQrPictureList = baseInfo.mergedQrPicture.split('|').filter(url => url.trim());
    }
    console.log('Processed mergedQrPictureList:', mergedQrPictureList);
    
    // Generate current time
    const currentTime = this.formatDateTime(new Date());
    
    // Process owner phone display (脱敏处理)
    let ownerPhoneDisplay = '184****0886'; // 默认值
    if (baseInfo && baseInfo.phone) {
      ownerPhoneDisplay = this.maskPhoneNumber(baseInfo.phone);
    }
    
    // Calculate warranty end date for each product and initialize package expand state
    if (baseInfo && baseInfo.ksgCarmembraneInfoList && baseInfo.constructionDate) {
      baseInfo.ksgCarmembraneInfoList = baseInfo.ksgCarmembraneInfoList.map((item, index) => {
        if (item.qualityWarrantyYears) {
          item.warrantyEndDate = this.calculateWarrantyEndDate(baseInfo.constructionDate, item.qualityWarrantyYears);
        }
        // 为每个产品添加套餐展开状态，默认收起
        item.packageExpanded = false;
        // 添加唯一标识用于状态管理
        item.productIndex = index;
        
        // 计算套餐总价值
        if (item.ksgProductItemList && item.ksgProductItemList.length > 0) {
          item.packageTotalValue = item.ksgProductItemList.reduce((sum, pkg) => {
            return sum + (pkg.totalPrice || 0);
          }, 0);
        } else {
          item.packageTotalValue = 0;
        }
        
        return item;
      });
    }
    
    this.setData({ 
      baseInfo,
      pictureList,
      qxImgList,
      mergedQrPictureList,
      currentTime,
      ownerPhoneDisplay
    });
  },
  
  /**
   * 切换套餐展开/收起状态
   * @param {Object} e 事件对象
   */
  togglePackageExpand(e) {
    const productIndex = e.currentTarget.dataset.index;
    const expandedKey = `baseInfo.ksgCarmembraneInfoList[${productIndex}].packageExpanded`;
    const currentExpanded = this.data.baseInfo.ksgCarmembraneInfoList[productIndex].packageExpanded;
    
    // 添加触觉反馈
    if (wx.vibrateShort) {
      wx.vibrateShort({
        type: 'light'
      });
    }
    
    this.setData({
      [expandedKey]: !currentExpanded
    });
    
    console.log(`套餐${productIndex}展开状态切换为:`, !currentExpanded);
  },
  
  /**
   * 显示错误信息
   * @param {string} message 错误信息
   */
  showError(message) {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 3000
    });
    
    // 延迟返回上一页
    setTimeout(() => {
      wx.navigateBack();
    }, 3000);
  },
  goBack() {
    wx.navigateBack();
  },
  
  // Format date to yyyy-MM-dd
  formatDate(dateString) {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
  },
  
  // Format datetime to yyyy-MM-dd HH:mm:ss
  formatDateTime(date) {
    if (!date) return '';
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },
  
  // Mask phone number for privacy (电话号码脱敏)
  maskPhoneNumber(phone) {
    if (!phone || phone.length < 11) return phone;
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  },
  
  // Calculate warranty end date (计算质保结束日期)
  calculateWarrantyEndDate(constructionDate, warrantyYears) {
    if (!constructionDate || !warrantyYears) return '';
    
    try {
      const startDate = new Date(constructionDate);
      const endDate = new Date(startDate);
      endDate.setFullYear(startDate.getFullYear() + parseInt(warrantyYears));
      
      return this.formatDate(endDate);
    } catch (error) {
      console.error('Error calculating warranty end date:', error);
      return '';
    }
  },
  
  // 预览施工图片
  previewImage(e) {
    const current = e.currentTarget.dataset.url;
    const urls = this.data.pictureList;
    if (!urls || urls.length === 0) {
      console.error('No pictures available');
      return;
    }
    wx.previewImage({
      current,
      urls
    });
  },

  // 预览清晰卷号图
  previewQxImage(e) {
    const current = e.currentTarget.dataset.url;
    const urls = this.data.qxImgList;
    if (!urls || urls.length === 0) {
      console.error('No qx images available');
      return;
    }
    wx.previewImage({
      current,
      urls
    });
  },

  // 预览单张图片（车架号和卷芯码合拍图、车辆和店招牌图）
  previewSingleImage(e) {
    const current = e.currentTarget.dataset.url;
    if (!current) {
      console.error('No image available');
      return;
    }
    wx.previewImage({
      current,
      urls: [current]
    });
  },

  // 预览车架号和卷芯码合拍图
  previewMergedQrImage(e) {
    const current = e.currentTarget.dataset.url;
    const urls = this.data.mergedQrPictureList;
    if (!urls || urls.length === 0) {
      console.error('No merged QR images available');
      return;
    }
    wx.previewImage({
      current,
      urls
    });
  },

  handleImageError(e) {
    const index = e.currentTarget.dataset.index;
    console.error(`Image load failed at index ${index}`);
  },

  // 分享给好友
  onShareAppMessage() {
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: 'KSG质保查询 - 专业汽车膜产品质保服务',
      path: '/pages/warranty/query/index',
      imageUrl: '/images/share-bg.jpg'
    };
  },

  // 初始化星空背景
  initStars() {
    const stars = [];
    for (let i = 0; i < 50; i++) {
      stars.push({
        left: Math.random() * 100,
        top: Math.random() * 100,
        size: Math.random() * 6 + 2,
        delay: Math.random() * 3
      });
    }
    this.setData({ stars });
  },

  // 复制质保单号
  copyWarrantyNumber(e) {
    const number = e.currentTarget.dataset.number;
    if (!number) {
      wx.showToast({
        title: '暂无质保单号',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    wx.setClipboardData({
      data: number,
      success() {
        wx.showToast({
          title: '质保单号已复制',
          icon: 'success',
          duration: 2000
        });
        // 添加触觉反馈
        if (wx.vibrateShort) {
          wx.vibrateShort({
            type: 'light'
          });
        }
      },
      fail() {
        wx.showToast({
          title: '复制失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },

  // 长按二维码提示
  showQrCodeTip() {
    wx.showModal({
      title: '关注公众号',
      content: '长按上方二维码图片，选择"识别图中二维码"即可关注KSG官方公众号获取更多服务',
      showCancel: true,
      cancelText: '知道了',
      confirmText: '打开扫一扫',
      confirmColor: '#9E2428',
      success: (res) => {
        if (res.confirm) {
          // 用户选择打开扫一扫
          this.openScanCode();
        }
      }
    });
    // 添加触觉反馈
    if (wx.vibrateShort) {
      wx.vibrateShort({
        type: 'medium'
      });
    }
  },

  // 打开扫码功能
  openScanCode() {
    wx.scanCode({
      success: (res) => {
        console.log('扫码结果:', res);
        if (res.result) {
          // 如果扫到了二维码，可以进一步处理
          wx.showToast({
            title: '扫码成功',
            icon: 'success'
          });
        }
      },
      fail: (err) => {
        console.log('扫码失败:', err);
        wx.showToast({
          title: '扫码取消',
          icon: 'none'
        });
      }
    });
  },

  // 拨打电话
  makePhoneCall(e) {
    const phone = e.currentTarget.dataset.phone;
    if (!phone) {
      wx.showToast({
        title: '电话号码错误',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    wx.showModal({
      title: '拨打电话',
      content: `确定要拨打客服电话 ${phone} 吗？`,
      confirmColor: '#9E2428',
      success(res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: phone,
            success() {
              console.log('拨打电话成功');
            },
            fail(err) {
              console.error('拨打电话失败:', err);
              wx.showToast({
                title: '拨打失败',
                icon: 'none',
                duration: 2000
              });
            }
          });
        }
      }
    });
  }
});
